<?php


namespace BoojasrFramework;


use BoojasrFramework\DependencyInjection\Compiler\AddCommandPass;
use BoojasrFramework\DependencyInjection\Compiler\TwigPass;
use BoojasrFramework\ServicesContainer\ContainerBuilder;
use BoojasrFramework\DependencyInjection\Compiler\DoctrinePass;
use BoojasrFramework\ServicesContainer\DependencyInjection\Compiler\PassContainer;
use Symfony\Component\Config\Resource\ClassExistenceResource;

class KernelRun implements RunInterface
{
    use ContainerAwareTrait;

    /**
     * @inheritDoc
     */
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new DoctrinePass());
        $this->addCompilerPassIfExists($container,AddCommandPass::class,PassContainer::TYPE_BEFORE_REMOVING);
        $container->addCompilerPass(new TwigPass());
    }

    /**
     * @inheritDoc
     */
    public function boot()
    {
    }

    /**
     * @inheritDoc
     */
    public function shutdown()
    {
    }

    private function addCompilerPassIfExists(ContainerBuilder $container, string $class, string $type = PassContainer::TYPE_BEFORE_OPTIMIZATION, int $priority = 0)
    {
        $container->addResource(new ClassExistenceResource($class));

        if (class_exists($class)) {
            $container->addCompilerPass(new $class(), $type, $priority);
        }
    }
}
